package com.link.base.base.product.controller;

import com.link.base.base.product.model.ShopCart;
import com.link.base.base.product.service.ShopCartService;
import com.link.base.user.model.CoreUser;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.UserUtil;
import com.link.core.cllog.LCLogger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author unknown
 * @date unknown
 * @comments 购物车
 */
@Controller
@RequestMapping("/link/shopCart")
public class ShopCartController extends BasicController<ShopCart> {

    @Resource
    private ShopCartService shopCartService;

    @Override
    public BasicService<ShopCart> getBasicService() throws Exception {
        return shopCartService;
    }

    @Override
    public void beforQueryAllOrExample(ShopCart entity, HttpServletRequest request) throws Exception {
        super.beforQueryAllOrExample(entity, request);
        entity.setEmpId(UserUtil.getUser().getId());
    }

    @Override
    public void beforInsert(ShopCart entity, HttpServletRequest request) throws Exception {
        super.beforInsert(entity, request);
        CoreUser user = UserUtil.getUser();
        if (entity.getProdId() == null) {
            throw new ServiceException("ORDER-085");
        }
        if (entity.getQty() <= 0) {
            throw new ServiceException("PRODUCT-029");
        }
        if (user.getAcctId() == null) {
            throw new ServiceException("ACCT-014");
        }
        //登陆类型为小程序
        if (BasicService.MP.equals(entity.getLoginType())) {
            //存储消费者id
            entity.setAcctId(user.getId());
        } else {
            entity.setEmpId(user.getId());
        }
        //是否有效
        entity.setActiveFlag("Y");
        entity.setSpCrStatus("N");
    }

    @Override
    public void beforDelete(ShopCart entity, HttpServletRequest request) throws Exception {
        super.beforDelete(entity, request);
        ShopCart vaildEntity = shopCartService.queryById(entity);
        if (vaildEntity == null) {
            throw new ServiceException("PRODUCT-033");
        }
        CoreUser user = UserUtil.getUser();
        //登陆类型为小程序

        if (BasicService.MP.equals(entity.getLoginType())) {
            if (!user.getId().equals(vaildEntity.getAcctId())) {
                throw new ServiceException("PUBLIC-031");
            }
        } else if (!user.getId().equals(vaildEntity.getEmpId())) {
            throw new ServiceException("PUBLIC-031");
        }

    }

    /**
     * 清空购物车
     */
    @RequestMapping(value = "/clearCart")
    @ResponseBody
    public Map<String, Object> clearCart(@JsonParam ShopCart entity, HttpSession session,
                                         HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            entity.setEmpId(UserUtil.getUser().getId());
            shopCartService.deleteByEmpId(entity);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 查询当前登录用户的购物车中的产品数量
     */
    @RequestMapping(value = "/queryEmpProdCount")
    @ResponseBody
    public Map<String, Object> queryEmpProdCount(HttpSession session,
                                                 HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            int count = shopCartService.queryEmpProdCount(new ShopCart());
            session.setAttribute("shopCartProdCount", count);
            result.put("count", count);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("count", 0);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 更新产品的数量
     */
    @RequestMapping(value = "/qtyUpdate")
    @ResponseBody
    public Map<String, Object> qtyUpdate(@JsonParam  ShopCart entity, HttpSession session,
                                         HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            ShopCart vaildEntity = shopCartService.queryById(entity);
            if (vaildEntity == null) {
                throw new ServiceException("PRODUCT-034");
            }
            if (!vaildEntity.getEmpId().equals(UserUtil.getUser().getAcctId())) {
                throw new ServiceException("PRODUCT-002！");
            }
            shopCartService.qtyUpdate(entity);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**根据shopItem的id删除购物车中的产品*/
    @RequestMapping(value = "/deleteShopItem")
    @ResponseBody
    public Map<String, Object> deleteShopItem(@RequestBody List<ShopCart> entitys, HttpSession session,
                                              HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            for (ShopCart item : entitys) {
                beforDelete(item, request);
            }
            shopCartService.batchDelete(entitys);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 查询小程序产品list
     * @author lujiang
     */
    @RequestMapping(value = "/queryByMpProdExamplePage")
    @ResponseBody
    public Map<String, Object> queryByMpProdExamplePage(@JsonParam QueryParams qps, @JsonParam ShopCart entity,
                                                        HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            this.beforQueryAllOrExample(entity, request);
            this.beforQueryExample(entity, request);
            result = shopCartService.queryByMpProdExamplePage(entity);
            result.put("success", true);
            List<ShopCart> list = (List<ShopCart>)result.get("rows");
            result.put("total", list.size());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * MP 加入购物车
     * @author lujiang
     * @created 18-10-30
     */
    @RequestMapping(value = "/insertShopCart")
    @ResponseBody
    public Map<String ,Object> insertShopCart(@RequestBody ShopCart shopCart ,
                                              HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String ,Object>  result = new HashMap<>();
        try {
            result = shopCartService.insertShopCart(shopCart);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return  result;
    }

    /**
     * MP 修改是否选中
     * @author lujiang
     * @created 18-10-30
     */
    @RequestMapping(value = "/selectedUpdate")
    @ResponseBody
    public Map<String ,Object> selectedUpdate(@RequestBody ShopCart shopCart ,
                                              HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String ,Object>  result = new HashMap<>();
        try {
            shopCartService.selectedUpdate(shopCart);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return  result;
    }
}
